package com.nian.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.UUID;

@MultipartConfig(location = "D:/imgUpload/", fileSizeThreshold = 1024 * 1024, maxFileSize = 1024 * 1024 * 5, maxRequestSize = 1024 * 1024 * 5 * 5)
@WebServlet("/admin/upFile.do")
public class UpFileServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        try {
            Part part = request.getPart("file");
            //获取文件后缀名，即文件类型
            String realFileName = part.getSubmittedFileName();
            String type = realFileName.substring(realFileName.lastIndexOf("."));
            //通过UUID 生成随机文件名
            String fileName = UUID.randomUUID().toString() + type;
            //获取项目下的该文件夹路径，必须先创建文件夹
            String path = "D:\\img/" + fileName;
            part.write(path);
            //将文件名信息回传至前端
            writer.write(fileName);
        } catch (Exception e) {
            writer.write(e.getMessage());
        }
    }
}
